package com.zl.service.impl;

import com.zl.common.Result;
import com.zl.dto.TsUserDto;
import com.zl.entity.TsUser;
import com.zl.mapper.UserMapper;
import com.zl.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("userService")
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;

    @Override
    public Result create(TsUserDto resources) {

        try {
            if(userMapper.findByUsername(resources.getUsername())!=null){
               return Result.error("用户名已存在");
            }

            if(userMapper.findByEmail(resources.getEmail())!=null){
                return Result.error("邮箱已存在");
            }
            // 默认密码 123456，此密码是加密后的字符
            resources.setPassword("e10adc3949ba59abbe56e057f20f883e");
            resources.setAvatar("https://i.loli.net/2019/04/04/5ca5b971e1548.jpeg");
            userMapper.save(resources);
            return Result.success();
        } catch (Exception e) {
            log.error("用户新增失败");
            return Result.error();
        }
    }

    @Override
    public Result update(TsUserDto resources) {
        try {
            long count = userMapper.update(resources);
            if (count == 0) {
                return Result.error("修改失败");
            }
            return Result.success();
        } catch (Exception e) {
            log.error("用户修改失败");
            return Result.error("系统异常");
        }
    }

    @Override
    public Result delete(Long id) {
        try {
            long count = userMapper.deleteById(id);
            if (count == 0) {
                return Result.error("删除失败");
            }
            return Result.success();
        } catch (Exception e) {
            log.error("用户删除失败");
            return Result.error("系统异常");
        }
    }

    @Override
    public Result updatePass(String username, String newPaas) {

        try {
            long count = userMapper.updatePass(username, newPaas);
            if (count == 0) {
                return Result.error("修改密码失败");
            }
            return Result.success();
        } catch (Exception e) {
            log.error("修改密码失败");
            return Result.error("系统异常");
        }
    }

    @Override
    public Result updateAvatar(String username, String url) {
        try {
            long count = userMapper.updateAvatar(username, url);
            if (count == 0) {
                return Result.error("修改头像失败");
            }
            return Result.success();
        } catch (Exception e) {
            log.error("修改头像失败");
            return Result.error("系统异常");
        }
    }

    @Override
    public TsUser findByName(String username) {
        return userMapper.findByName(username);
    }
}
